package com.tsfyun.scm.service.impl.support;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.tsfyun.common.base.dto.FileDTO;
import com.tsfyun.common.base.exception.ServiceException;
import com.tsfyun.common.base.extension.OrderItem;
import com.tsfyun.common.base.extension.ServiceImpl;
import com.tsfyun.scm.dto.support.FeedbackDTO;
import com.tsfyun.scm.dto.support.FeedbackQTO;
import com.tsfyun.scm.entity.support.Feedback;
import com.tsfyun.scm.mapper.support.FeedbackMapper;
import com.tsfyun.scm.service.file.IUploadFileService;
import com.tsfyun.scm.service.support.IFeedbackService;
import com.tsfyun.scm.util.TsfWeekendSqls;
import com.tsfyun.scm.vo.support.FeedbackVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;


/**
 * <p>
 * 意见反馈 服务实现类
 * </p>
 *
 *
 * @since 2020-09-23
 */
@Service
public class FeedbackServiceImpl extends ServiceImpl<Feedback> implements IFeedbackService {

    @Autowired
    private IUploadFileService uploadFileService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(FeedbackDTO dto) {
        Feedback feedback = beanMapper.map(dto,Feedback.class);
        super.saveNonNull(feedback);
        //关联图片
        FileDTO fileDTO = new FileDTO(dto.getPicId(),"feedback");
        uploadFileService.relateFile(feedback.getId().toString(),fileDTO);
    }

    @Override
    public PageInfo<Feedback> pageList(FeedbackQTO qto) {
        TsfWeekendSqls wheres = TsfWeekendSqls.<Feedback>custom().andLike(true,Feedback::getMemo,qto.getMemo())
                .andLike(true,Feedback::getContact,qto.getContact()).andEqualTo(true,Feedback::getQuestionType,qto.getQuestionType());
        PageInfo<Feedback> pageInfo = super.pageList(qto.getPage(),qto.getLimit(),wheres, Lists.newArrayList(OrderItem.desc("dateCreated")));
        return pageInfo;
    }

    @Override
    public FeedbackVO detail(Long id) {
        //图片信息单独调用文件接口
        Feedback feedback = super.getById(id);
        Optional.ofNullable(feedback).orElseThrow(()->new ServiceException("意见反馈不存在，请确认是否已被删除"));
        return beanMapper.map(feedback,FeedbackVO.class);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void remove(Long id) {
        Feedback feedback = super.getById(id);
        Optional.ofNullable(feedback).orElseThrow(()->new ServiceException("意见反馈不存在，请确认是否已被删除"));
        super.removeById(id);
    }
}
